<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <link th:href="@{/img/Bandit.ico}" rel="icon">
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet">
    <style>
        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select{
            margin-top: -10px;
            margin-left: -15px;
            margin-right: -15px;
        }
    </style>
</head>
<body>
<div class="layui-layout layui-layout-admin">
    <div th:replace="~{commons/common::BackHeader}"></div>
    <div class="layui-body">

        <table id="user-list" lay-filter="userTable"></table>

    </div>
</div>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/layui/layui.js}"></script>
<script type="text/html" id="userBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="userHeadBar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="delCheckIDS">批量删除</button>
    </div>
</script>
<script th:inline="javascript">
    var permissionList = [[${permissionList}]]
</script>
<script type="text/javascript"  th:inline="none">

    var prefix_back = '/back/user';
    var prefix_front = '/front';

    layui.use(['element', 'layer', 'util','table','form'], function() {
        var element = layui.element
            , layer = layui.layer
            , util = layui.util
            , form = layui.form
            , table = layui.table
            , $ = layui.$;
        //执行渲染
        table.render({
            elem: '#user-list' //指定原始表格元素选择器（推荐id选择器）
            ,url: prefix_back + '/query'
            ,width: 1600
            ,toolbar: '#userHeadBar'
            ,cols: [[
                {type:'checkbox', fixed: 'left'}
                ,{field:'id',fixed:true, title: 'id', sort: true}
                ,{field:'username',fixed:true, title: '用户名'}
                ,{field:'permission',fixed:true,title: '权限',templet:function (d){
                        let html = `<select name="permission" lay-filter="select">`;
                        for(let i=0;i<permissionList.length;i++){
                            html += `<option value='`+permissionList[i]+`'`;
                            if(d.permission==permissionList[i]){
                                html+=`selected>`+permissionList[i]+`</option>`;
                            }else html +=`>`+permissionList[i]+`</option>`
                        }
                        html +=`</select>`
                        return html;
                    }}
                ,{fixed: 'right', title:'操作', toolbar: '#userBar', width:200}
            ]] //设置表头
            ,page: true
            ,limit:10
            ,done:function (res, curr, count){
                $(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow', 'visible');
            }
        });

        //toolBar
        table.on('tool(userTable)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            if(layEvent === 'del'){//删除
                layer.confirm('确定要删除吗', function(index){
                    $.ajax({
                        url: prefix_back + "/delete?id=" + data.id,
                        success:function (){
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            layer.close(index);
                        }
                    })
                });
            }
        });

        //批量删除
        table.on('toolbar(userTable)', function(obj){
            //获取选中的数据
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'delCheckIDS':
                    if(checkStatus.data.length<=0){
                        layer.msg('未选中任何值');
                        break;
                    }else {
                        let len = checkStatus.data.length;
                        let dataArray = [];
                        for(let i = 0;i<len;i++){
                            dataArray.push(checkStatus.data[i].id)
                        }
                        layer.confirm('确定要删除吗？',{
                            btn:['确认','取消']
                        },function () {
                            layer.msg('删除成功');
                            // layer.alert(JSON.stringify(dataArray));
                            //提交后台删除
                            $.ajax({
                                type:'POST',
                                url: prefix_back + "/deleteByIDS",
                                data:{
                                    "ids":dataArray.toString()
                                },
                                dataType:'json'
                                ,success(){
                                    setTimeout(function(){
                                        parent.layer.closeAll();
                                        window.location.reload();
                                    },1000)
                                }
                            })
                        },function () {
                            layer.closeAll()
                        })
                        break;
                    }
            }
        });

        //监听下拉框提交
        form.on('select(select)', function (data) {
            //获取当前行tr对象
            var value = data.value;
            var elem = data.othis.parents('tr');
            var id= elem.first().find('td').eq(1).text();
            console.log(value)
            console.log(id);
            $.ajax({
                type: 'POST',
                url: prefix_back+'/perEdit',
                data:{
                    "id":id
                    ,"permission":value
                },
                dataType: 'json',
                success:function (res) {
                    console.log(res);
                }
            })

        })
    });
    layui.each($('select'), function (index, item) {
        var elem = $(item);
        elem.val(elem.data('value')).parents('div.layui-table-cell').css('overflow', 'visible');
    });
</script>
</body>
</html>